package cn.tedu.coolshark.filter;

import cn.tedu.coolshark.pojo.vo.UserVO;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",urlPatterns = {"/admin.html","/insertBanner.html","/insertProduct.html","/product/delete"})
public class MyFilter implements Filter {
    //初始化时执行的方法
    public void init(FilterConfig config) throws ServletException {
    }
    //销毁时执行的方法
    public void destroy() {
    }

    //请求到资源之前执行的方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("经过了过滤器!");
        HttpServletRequest rt = (HttpServletRequest) request;
        HttpServletResponse re = (HttpServletResponse) response;
        //得到会话对象
        HttpSession session = rt.getSession();
        //得到当前登录的用户对象
        UserVO u = (UserVO) session.getAttribute("user");
        if (u != null) {//登录过
            chain.doFilter(request, response);//放行
        }else{//未登录
            //让客户端重定向到登录页面
            re.sendRedirect("/login.html");
        }
    }
}
